/*======================================================================
 * JavaScript framework of BX.
 * Author ：  zhangaoxiang
 *====================================================================*/

BX = function(){
	this.cn_char_length = 3;	
	this.IsVirtual = true ;
	this.skin = "";
	this.ContextPath = this.ContextRoot();
	this.ResourcesPath = this.ContextRoot()+"/assets" +this.skin;
	this.IsUseAJAX = true;
	this.IsAjaxOne = false;
}
BX.VERSION = '1.0.0';
BX.MASK_LAYER_ID = "bx_mask_layer";
BX.prototype.Host=function(){
	return window.location.host;      
}
BX.prototype.Domain=function(){
	return document.domain;         
}
BX.prototype.ContextRoot=function(){
	if(this.IsVirtual){
		var pathname = window.document.location.pathname;
		if(pathname.substring(0,1)!="/"){
			pathname = "/"+pathname ;
		}
		return pathname.substr(0,pathname.substr(1).indexOf("/")+1);
	}
	else{
		return "" ;
	}
}
BX.prototype.ProjectURL=function(){
	return "http://"+this.Host()+this.ContextRoot();
}
BX.prototype.CallBack = function(){
	this.Layout();   //页面重新加载后,再次初始样式
	this.MLayout();
    this.Message();  //触发消息
    this.RegisterSuggest(); //注册suggest控件的事件
    this.RegisterCalendar();    //注册Calendar控件事件
}
BX.prototype.MaskLayer = function(show){
 	var masklayer = document.getElementById(BX.MASK_LAYER_ID);
 	if(show){  
 		if(masklayer === null){
 			masklayer = document.createElement("DIV");
	    	document.body.appendChild(masklayer);
	    	masklayer.id = BX.MASK_LAYER_ID;
    	}
    	var isIE = (document.all) ? true : false;
		var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6);
		masklayer.style.width=masklayer.style.height="100%";
		masklayer.style.position= !isIE6 ? "fixed" : "absolute";
		masklayer.style.top=masklayer.style.left=0;
		masklayer.style.background="#666"; 
		masklayer.style.filter="alpha(opacity=30)";  //IE透明度
		masklayer.style.opacity = (30/100);    //火狐、谷歌透明度
		masklayer.style.zIndex = "9999"; 
		masklayer.style.display = "block";
		if(isIE6){
			//this.RestoreDV();
			//window.attachEvent("onresize",this.RestoreDV);
		}
 	}
 	else{
 		if(masklayer !== null){masklayer.style.display = "none";}
 	}
}
BX.prototype.Toast = function(msg){
	layer.msg(msg);
}
/*======================================================================
 * 参数列表：0-message,1-callback,
 *====================================================================*/
BX.ALERT_DIALOG_ID   = 'x_alert_msg_box';
BX.ALERT_DIALOG_HTML = '<div class="x-msgbox-hd" hidefocus="hidefocus">{0}</div>'+
                       '<a class="x-msgbox-close x-close" hidefocus="hidefocus"><b class="x-ico x-ico-close" data-x="close" data-target="'+BX.ALERT_DIALOG_ID+'">x</b></a>'+
                       '<div class="x-msgbox-bd">'+
                       '<div class="x-msgbox-iconText ">'+
                       '<span class="x-msgbox-iconText-icon"><b class="x-ico x-ico-info"></b></span>'+
                       '<div class="x-msgbox-iconText-text"><div class="x-msgbox-title">{1}</div>{2}</div>'+
                       '</div></div>'+
                       '<div class="x-msgbox-ft">'+
                       '<div class="x-msgbox-ft-text">{3}</div>'+
                       '<div class="x-msgbox-ft-btns">{4}</div>'+
                       '</div>';
BX.ALERT_DIALOG_BTN_OK     = '<button type="button" class="btn btn-sm btn-default btn-primary" data-x="callback" data-target="'+BX.ALERT_DIALOG_ID+'">确定</button>';
BX.ALERT_DIALOG_BTN_CLOSE     = '<button type="button" class="btn btn-sm btn-default" data-x="close" data-target="'+BX.ALERT_DIALOG_ID+'">关闭</button>';
BX.ALERT_DIALOG_BTN_CANCEL = '<button type="button" class="btn btn-sm btn-default" data-x="close" data-target="'+BX.ALERT_DIALOG_ID+'">取消</button>';
BX.ALERT_DIALOG_ARGUMENTS  = new Array();
BX.prototype.Alert = function(msg,fn,args){
	if(arguments.length>1){
		BX.ALERT_DIALOG_ARGUMENTS[0] = fn;
		for(var i=2;i<arguments.length;i++){
			BX.ALERT_DIALOG_ARGUMENTS[i-1]=arguments[i];
		}
	}
	this.MaskLayer(true);
	var dialog = document.getElementById(BX.ALERT_DIALOG_ID);
	var alert_html;
	if(arguments.length>1){
		alert_html = BX.ALERT_DIALOG_HTML.replace(/\{0}/g,"温馨提示").replace(/\{1}/g,arguments[0]).replace(/\{2}/g,"&nbsp;").replace(/\{3}/g,"").replace(/\{4}/g,BX.ALERT_DIALOG_BTN_OK+"&nbsp;"+BX.ALERT_DIALOG_BTN_CANCEL);
	}
	else{
		alert_html = BX.ALERT_DIALOG_HTML.replace(/\{0}/g,"温馨提示").replace(/\{1}/g,arguments[0]).replace(/\{2}/g,"&nbsp;").replace(/\{3}/g,"").replace(/\{4}/g,BX.ALERT_DIALOG_BTN_CLOSE);
	}
	if(dialog === null){
		dialog = document.createElement("div");
		document.body.appendChild(dialog);
		dialog.id = BX.ALERT_DIALOG_ID;
		dialog.tabindex = "0";
		dialog.className = "x-msgbox";
	}
	dialog.innerHTML = alert_html;
	
	var isIE = (document.all) ? true : false;
	var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6);
	dialog.style.position = !isIE6 ? "fixed" : "absolute";
	dialog.style.top = dialog.style.left = "50%";
	dialog.style.marginTop = "-150px";
	dialog.style.marginLeft = "-228px";
	dialog.style.display = "block";
	dialog.style.zIndex = "10000";
}
BX.prototype.Message = function(){
    var msg = $("#MessageZone").html();
    if(msg !==undefined && msg.length != 0) this.Alert(msg);
}
BX.prototype.ChkSlt = function(){
	var result = false;
	$("input[name='"+arguments[0]+"']").each(function(){
		if(this.checked){
			result = true;
			return false;
		}
	})
	if(result){
		return true;
	}
	else{
		this.Alert("必须选择一项，谢谢合作!");
		return false;
	}
}
BX.prototype.Modal = function(url,args,callback,width,height,title){
	var index = layer.open({
			    type: 2,
			    border: [10, 0.9, '#fff'],
			    title:title==undefined?"&nbsp;":title,
			    maxmin: true,
			    fadeIn: 100,
			    content:  this.ContextPath+"/"+url,
			    area: [width, height],
			    end: function()
			    {
			    	if(callback)
			    	{
			    		if(callback.lastIndexOf(")")!=-1)
				    		eval(callback);
				    	else
				    		eval(callback+'()');
			    	}
			    }
			});
	return index;
}
BX.prototype.CloseLayer = function(){
	parent.layer.close(parent.layer.getFrameIndex(window.name));
}
BX.prototype.Layout = function(){
	//查询表格记录为空时的布局处理
	$('.empty-table-td').attr("colspan",$('.empty-table-td').parent().parent().parent().children("thead").children().children().length);
    $('.empty-table-td>div').show();
    //排序处理
    $("table[data-x='datalist'] thead tr").each(function(){
    	var sortField  = $("#sys_p_sort_field");
    	var sortMethod = $("#sys_p_sort_method").val();
    	$(this).children().each(function(){
    		var field_a = $(this).attr("sort")
    		var field_v = sortField.val()
    		if(typeof field_a != "undefined"){
    			if(field_a==field_v){
    				if(sortMethod == "DESC"){
    					$(this).addClass("x-sort-desc")
    				}
    				else{
    					$(this).addClass("x-sort-asc")
    				}
    			}
    			else{
    				$(this).addClass("x-sort")
    			}
    			$(this).click(function(){X.PageSort(field_a)})
    		}
    	})
    })
}
BX.prototype.MLayout = function(){
	var target = $('[class~="active"]').data("target")
	var length = $('[data-mv="'+target+'"').length
	if(length==0){
		$("#vnav-item").css('display','none')
		$("#main-zone").css('left','64px')
	}else{
		$("#vnav-item").css('display','block')
		$("#main-zone").css('left','244px')
	}
}
BX.prototype.RegisterSuggest = function(){
	$('[data-x="suggest"]').suggest();
}
BX.prototype.RegisterCalendar = function(){
	$('[data-type="Date"]').click(function(){WdatePicker()})
	$('[data-type="DateTime"]').click(function(){WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})})
}
BX.prototype.PagerInit = function(){
	$("#sys_p_count").val("");
	$("#sys_i_count").val("");
	$("#sys_p_size").val("");
	$("#sys_p_index").val("");
	$("#sys_p_sort_method").val("");
	$("#sys_p_sort_field").val("");
	$("#sys_p_high_search").val("");
}
BX.prototype.Page  = function(){
	$("#sys_p_index").val(arguments[0]);
	this.Submit($("#sys_default_method").val());
}
BX.prototype.PageSize = function(){
	$("#sys_p_size").val(arguments[0]);
	this.Submit($("#sys_default_method").val());
}
BX.prototype.PageSort = function(){
	$("#sys_p_sort_method").val($("#sys_p_sort_method").val()=="DESC"?"ASC":"DESC");
	$("#sys_p_sort_field").val(arguments[0]);
	this.Submit($("#sys_default_method").val());
}
BX.prototype.Menu = function(){
	if(this.IsUseAJAX){
		ajaxAnywhere.getAJAX(arguments[0],"MainZone");
	}
	else{
		location.href=arguments[0];
	}
}
BX.prototype.Tab = function(){
	this.PagerInit();
	$($("form")[0]).attr("action",arguments[0]);
	this.Submit(null,"0");
}
BX.prototype.Search = function(){
	this.PagerInit();
    this.Submit($("#sys_default_method").val(), 1);
 	return false;
}
BX.prototype.submit = function(){
	var method = arguments[0];
	var check  = arguments[1];
	var form = document.forms.length==0?null:document.forms[0];
	if(form!=null){
		var s1=form.action.split("//");
		var s2=s1.length>1?s1[1].substring(s1[1].indexOf("/")):form.action;
		form.action = s2;
	
		if((check=="1"&&this.Check(form))||check!="1"){
			$("#sys_action_method").attr("name",method==null?"":"method:"+method);
			if(this.IsUseAJAX && !this.IsAjaxOne){
				ajaxAnywhere.formName="MainFrm";
				ajaxAnywhere.getZonesToReload=function(){return "MainZone,MessageZone";}
				ajaxAnywhere.submitAJAX();
			}
			else{
				form.submit();
			}
		}
	}
}
BX.prototype.SubmitBack = function(){
	switch(arguments.length){
	case 0:
		this.submit('execute','0');
		break;
	case 1:
		this.submit(arguments[0],'0');
		break;
	}
	return false;
}
BX.prototype.Submit = function(){
	switch(arguments.length){
	case 0:
		this.submit('execute','1');
		break;
	case 1:
		this.submit(arguments[0],'1');
		break;
	case 2:
		this.submit(arguments[0],arguments[1]);
		break;
	case 3:
		ajaxAnywhere.noFilter=arguments[2];
		this.submit(arguments[0],arguments[1]);
		ajaxAnywhere.noFilter=false;
		break;
	}
	return false;
}
/*======================================================================
 * 表单合法验证
 * Author ：      zhangaoxiang 
 *====================================================================*/
BX.prototype.RealLength = function( sString )
{
	var iLength = 0;	// 真实长度记数器
	for( i = 0; i < sString.length; i ++ )
	{
		if(sString.charCodeAt(i)>255)
		{
			iLength += parseInt(this.cn_char_length);
		}
		else
		{
			iLength += 1;
		}
	}
	return iLength;
}
BX.prototype.IsIntVal = function(value){
	var returnValue = true;
	var re =  new RegExp("^(([0-9]+)|-([0-9]+))$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsInt = function(value){
	var returnValue = true;
	var re =  new RegExp("^([0-9]+)$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsFloat = function(value){
	var returnValue = true;
	var re =  new RegExp("^(([0-9]+)|([0-9]+\\.[0-9]+))$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsPrice = function(value){
	var returnValue = true;
	fValue = parseFloat(value);
	if(fValue + "" == "NaN")
	{
		returnValue=false;
	} 
	if (fValue <= 0) {
		returnValue=false; // 价格必须大于0
	}
	return returnValue;
}
BX.prototype.IsValid = function(value){
	var returnValue = true;
	var re =  new RegExp("^[A-Za-z0-9_]*$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsLetter = function(value){
	var returnValue = true;
	var re =  new RegExp("^([A-Za-z]*)$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsUpperCase = function(value){
	var returnValue = true;
	var re =  new RegExp("^([A-Z]*)$");
	if(value.search(re) == -1)
	{
	returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsDate = function(value)
{
	var re = new RegExp("^([1-9][0-9]{3}-(((2|(02))-((0{0,1}[1-9])|([12][0-9])))|(((0{0,1}[469])|(11))-((0{0,1}[1-9])|([12][0-9])|(30)))|(((0{0,1}[13578])|([1][02]))-((0{0,1}[1-9])|([12][0-9])|(3[01])))))$");
	if(value.search(re) == -1)
	{
		return false;
	}else{
		return true;
	}
}
BX.prototype.IsDateTime = function(value)
{
   var reg = /^[1-9][0-9]{3}-(0?[1-9]|1[0|1|2])-(0?[1-9]|[1|2][0-9]|3[0|1]) (0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1|2|3|4|5][0-9]):(0?[0-9]|[1|2|3|4|5][0-9])$/;
   if(reg.test(value))
   {
   	   return true;
   }
   else
   {
   	   return false;
   }
}
BX.prototype.IsTelephone = function(str)   
{
	for(ilen=0;ilen<str.length;ilen++)
	{
		if(str.charAt(ilen) < '0' || str.charAt(ilen) > '9' )
		{
		if((str.charAt(ilen)!='-')&&(str.charAt(ilen)!='*')&&(str.charAt(ilen)!='(')&&(str.charAt(ilen)!=')'))
			return false;
		}   
	}
	return true;
}
BX.prototype.IsPostCode = function(sValue)
{
	if( sValue == null )
	{
		return false;
	}
	if( sValue.length != 6 )
	{
		return false;
	}
	else
	{
		var re =  new RegExp("^([0-9]+)$");
		for( i = 0; i < 6; i ++ )
		{
			if(sValue.search(re) == -1)
			{
				return false;
			}
		}
	}
	return true;
}
BX.prototype.IsEmail = function(value){
	var returnValue = true;
	//var re =  new RegExp("^[A-Za-z][A-Za-z0-9_]*@([A-Za-z0-9]+[.])+([A-Za-z]{2,3})$");
	var re =  new RegExp("^[A-Za-z0-9_]*@([A-Za-z0-9]+[.])+([A-Za-z]{2,3})$");
	if(value.search(re) == -1)
	{
		returnValue=false;
	}
	return returnValue;
}
BX.prototype.IsURL = function(value)
{
	return (value.substring(0,7)=="http://");
}
BX.prototype.IsPassword = function(sValue)
{
	if( sValue == null ){
		return false;
	}
	if( sValue.length < 6 ){
		return false;
	}
	else{
		var re =  new RegExp("^([0-9]+)$");
		if(sValue.search(re) == -1){
			return true;
		}
		else
			return false;
	}
}
BX.prototype.IsASCII = function( cValue )
{
	var sFormat = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
	var iLocation = sFormat.indexOf( cValue );
	return( iLocation != -1 );
}
BX.prototype.Check = function(form){
	var elements = form.elements;
	var len = elements.length;
	for(var i=0;i<len;i++)
	{
		var field = elements[i];
		if(field.type=="file") this.IsAjaxOne = true;
		if((field.type=="text" || field.type=="textarea"|| field.type=="file"|| field.type=="hidden" ||field.type=="password"))
		{
			if(field.type == "textarea") 
			{
				//X.BindUeditorHTML(); //对Ueditor控件值进行绑定
			}
			if(field.getAttribute("data-must")=="1" && field.value=="")
			{
				this.Alert("' " + field.title+ " ' 必须录入，谢谢合作！");
				field.focus();
				return false;
			}
			if(field.getAttribute("data-length")!= undefined)
			{
				var _len = this.RealLength(field.value);
				if(_len!=field.getAttribute("data-length"))
				{
					this.Alert("' " + field.title+ " ' 长度必须等于"+field.getAttribute("data-length"));
					field.focus();
				    return false;
				}
			}
			if(field.getAttribute("data-maxlen")!= undefined)
			{
				var _len = this.RealLength(field.value);
				if(_len>field.getAttribute("data-maxlen"))
				{
					this.Alert("' " + field.title+ " ' 长度必须小于"+field.getAttribute("data-maxlen"));
					field.focus();
				    return false;
				}
			}
			if(field.getAttribute("data-minlen")!= undefined)
			{
				var _len = this.RealLength(field.value);
				if(_len<field.getAttribute("data-minlen"))
				{
					this.Alert("' " + field.title+ " ' 长度必须大于"+field.getAttribute("data-minlen"));
					field.focus();
				    return false;
				}
			}
			if(field.value=="" ) continue;
			switch (field.getAttribute("data-type")){
				case "Email":
				    if(!this.IsEmail(field.value))
				    {
						this.Alert("' " + field.title+" ' 必须为合法的Email地址！");
						field.focus();
						return false;
				    }
					break;
				case "URL":
					if(!this.IsURL(field.value))
				    {
						
						this.Alert("' " +field.title+" ' 必须以http://开头的合法字符！");
						field.focus();
						return false;
				    }
					break;
				case "Telephone":
					if(!this.IsTelephone(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是正确的电话号码！");
						field.focus();
						return false;
				    }
					break;
				case "PostCode":
					if(!this.IsPostCode(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须为合法的邮政编码！");
						field.focus();
						return false;
				    }
					break;
				case "Date":
					if(!this.IsDate(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是格式为[YYYY-MM-DD]的合法日期！");
						field.focus();
						return false;
				    }
					break;
				case "DateTime":
					if(!this.IsDateTime(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是格式为[YYYY-MM-DD hh:mm:ss]的合法日期时间！");
						field.focus();
						return false;
				    }
					break;
				case "Int":
					if(!this.IsInt(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是数字！");
						field.focus();
						return false;
				    }
					break;
				case "IntVal":
					if(!this.IsIntVal(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是数字！");
						field.focus();
						return false;
				    }
					break;
				case "Float":
					if(!this.IsFloat(field.value))
				    {
						this.Alert("' " +field.title+" ' 必须是实数！");
						field.focus();
						return false;
				    }
					break;
				case "LetterDigit":
				   if(!IsValid(field.value))
				   {
						this.Alert("' " +field.title+" ' 只能是数字和字母！");
						field.focus();
						return false;				   	    
				   }
				   break;
				case "Letter":
				   if(!this.IsLetter(field.value))
				   {
						this.Alert("' " +field.title+" ' 只能是字母！");
						field.focus();
						return false;				   	    
				   }
				   break;
				case "UpperCase":
				   if(!this.IsUpperCase(field.value))
				   {
						this.Alert("' " +field.title+" ' 只能是大写字母！");
						field.focus();
						return false;				   	    
				   }
				   break;
				case "Password":	
				  if(!this.IsPassword(field.value))
				   {
						this.Alert("' " +field.title+" ' 长度不能小于6位,且不能全部为数字！");
						field.focus();
						return false;				   	    
				   }
				   break;
			}

		}
		//下面处理 radio 和 checkbox
		if(field.type == "radio")
		{
			if(field.getAttribute("data-must")=="1")
			{
			    var flag = false;
				var _ele = document.getElementsByName(field.getAttribute("name"));
				for(var j=0;j<_ele.length;j++)
				{
					if(_ele[j].checked)
					{
						flag = true;
						break;
					}
				}
				if(!flag)
				{
					this.Alert("' " +field.title+" ' 必须选择一个，谢谢合作！");
					field.focus();
					return false;
				}
			}
		}
		//下面处理 select
		if(field.type.indexOf("select")>=0)
		{
			if(field.getAttribute("data-must")=="1" && field.value=="")
			{
				this.Alert("' " + field.title+ " ' 必须选择，谢谢合作！");
				field.focus();
				return false;
			}
		}
	}
	return true;
}
BX.TREE_CLOSE_IMAGE_DATA = "";
BX.TREE_OPEN_IMAGE_DATA  = "";
X = new BX();
/*======================================================================
 * 声明式多选框（全选/反选）
 * Author ：      zhangaoxiang 
 *====================================================================*/
+function($){
	"use strict";
	var choice = '[data-x="mult"]';
	var Choice = function(el){
		$(el).on('click',choice,this.choice);
	}
	Choice.prototype.choice = function(e){
		var $this = $(this);
		var selector = $this.attr('data-target');
		$("input[name='"+selector+"']").prop('checked', $this.prop('checked'));
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.choice')

		    if (!data) $this.data('bs.choice', (data = new Choice(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.choice

	$.fn.choice             = Plugin
	$.fn.choice.Constructor = Choice
	
	$.fn.choice.noConflict = function () {
	  $.fn.choice = old
	  return this
	}
	
	$(document).on('click.bs.choice.data-api', choice, Choice.prototype.choice)
}(jQuery);
/*======================================================================
 * 声明式多选框（Tree节点操作）
 * Author ：      zhangaoxiang 
 * data-x="tree-check"  data-id = "id"  data-pid = "pid"
 *====================================================================*/
+function($){
	"use strict";
	var tree = '[data-x="tree-check"]';
	var Select = function(el){
		$(el).on('click',selection,this.select);
	}
	Select.prototype.select = function(e){
		var $this = $(this);
		var selector = $this.attr('data-id');
		$("input[data-pid='"+selector+"']").prop('checked', $this.prop('checked'));
		$("input[data-pid='"+selector+"']").each(function(){treeselect(this,$this)});
	}
	function treeselect(element,current)
	{
		var selector = $(element).attr('data-id');
		$("input[data-pid='"+selector+"']").prop('checked', $(current).prop('checked'));
		$("input[data-pid='"+selector+"']").each(function(){treeselect(this,current)});
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.tree.select')

		    if (!data) $this.data('bs.tree.select', (data = new Select(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.select

	$.fn.select             = Plugin
	$.fn.select.Constructor = Select
	
	$.fn.select.noConflict = function () {
	  $.fn.select = old
	  return this
	}
	
	$(document).on('click.bs.tree.data-api', tree, Select.prototype.select)
}(jQuery);
/*======================================================================
 * 声明式TREE（展开、合起）
 * Author ：      zhangaoxiang 
 * data-x="tree-expand"  data-id = "id"  data-pid = "pid"
 *====================================================================*/
+function($){
	"use strict";
	var tree = '[data-x="tree-expand"]';
	var Select = function(el){
		$(el).on('click',selection,this.select);
	}
	Select.prototype.select = function(e){
		var $this = $(this);
		var show = true;
		if($this.attr('src') === BX.TREE_CLOSE_IMAGE_DATA)
		{
			$this.attr('src',BX.TREE_OPEN_IMAGE_DATA);
			show = true;
		}
		else
		{
			$this.attr('src',BX.TREE_CLOSE_IMAGE_DATA);
			show = false;
		}
		
		var selector = $this.parent().parent().attr('data-id');
		if(show)
		{
			$("tr[data-pid='"+selector+"']").show();
			$("img[data-pid='"+selector+"']").attr('src',BX.TREE_CLOSE_IMAGE_DATA);
		}
		else
		{
			$("tr[data-pid='"+selector+"']").hide();
			$("tr[data-pid='"+selector+"']").each(function(){treeexpand(this,$this,show)});
		}
	}
	function treeexpand(element,current,show)
	{
		var selector = $(element).attr('data-id');
		if(show)
		{
			$("tr[data-pid='"+selector+"']").show();
			$(element).attr('src',BX.TREE_OPEN_IMAGE_DATA);
			$("tr[data-pid='"+selector+"']").each(function(){treeexpand(this,current,show)});
		}
		else
		{
			$("tr[data-pid='"+selector+"']").hide();
			$(element).attr('src',BX.TREE_CLOSE_IMAGE_DATA);
		}
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.tree.select')

		    if (!data) $this.data('bs.tree.select', (data = new Select(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.select

	$.fn.select             = Plugin
	$.fn.select.Constructor = Select
	
	$.fn.select.noConflict = function () {
	  $.fn.select = old
	  return this
	}
	
	$(document).on('click.bs.tree.data-api', tree, Select.prototype.select)
}(jQuery);
/*======================================================================
 * 声明式消息对话框关闭
 * Author ：      zhangaoxiang 
 *====================================================================*/
+function($){
	"use strict";
	var close = '[data-x="close"]';
	var Msgbox = function(el){
		$(el).on('click',close,this.close);
	}
	Msgbox.prototype.close = function(e){
		var $this = $(this);
		var selector = $("#"+$this.attr('data-target'));
		BX.ALERT_DIALOG_ARGUMENTS.length=0;
		selector.hide();
		X.MaskLayer(false);
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.msgbox')
		    if (!data) $this.data('bs.msgbox', (data = new Msgbox(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.msgbox

	$.fn.msgbox             = Plugin
	$.fn.msgbox.Constructor = Msgbox
	
	$.fn.msgbox.noConflict = function () {
	  $.fn.msgbox = old
	  return this
	}
	
	$(document).on('click.bs.msgbox.data-api', close, Msgbox.prototype.close)
}(jQuery);
/*======================================================================
 * 声明式消息对话框回调
 * Author ：      zhangaoxiang 
 *=====================================================================*/
+function($){
	"use strict";
	var call = '[data-x="callback"]';
	var Msgbox = function(el){
		$(el).on('click',call,this.call);
	}
	Msgbox.prototype.call = function(e){
		var $this = $(this);
		
		var selector = $("#"+$this.attr('data-target'));
		selector.hide();
		X.MaskLayer(false);
		
		var fun;
		var argument = BX.ALERT_DIALOG_ARGUMENTS;
		if(argument.length>1){
		  var args="";
		  for(var i = 1;i<argument.length-1;i++){
			if(typeof argument[i] == "string"){
				args+= "'" + argument[i] + "',";
			} 
			else{
				args+= argument[i] + ",";
			}
		  }
		  if(typeof argument[i] == "string"){
			  args += "'" + argument[argument.length-1] + "'";
		  }
		  else{
			  args += argument[argument.length-1];
		  }
		  fun = argument[0] + "(" + args + ")";
		}
		else{
			if(argument[0].lastIndexOf(")")==-1)
				fun = argument[0] + "()";
			else
				fun = argument[0]
        }
		eval(fun);
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.msgbox')
		    if (!data) $this.data('bs.msgbox', (data = new Msgbox(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.msgbox

	$.fn.msgbox             = Plugin
	$.fn.msgbox.Constructor = Msgbox
	
	$.fn.msgbox.noConflict = function () {
	  $.fn.msgbox = old
	  return this
	}
	
	$(document).on('click.bs.msgbox.data-api', call, Msgbox.prototype.call)
}(jQuery);
/*======================================================================
 * 声明式搜索提示控件
 * Author ：      zhangaoxiang 
 * data-x='suggest' data-provide='url' data-adapter='ref_id' data-callback='callback function' data-ignorenull='false|true'
 * data-lineheight='32' data-width="280" data-fontsize="16" data-maxlines="8"
 * data-multword="false" data-separator=","
 * 
 *====================================================================*/
+function ($) {
    'use strict';
	// Suggest CLASS DEFINITION
	// ========================
	var Suggest = function(control,options) {
		this.id = control.id
		this.control= control
		this.widget = null
		this.index = -1
		this.global_focus_flag=false
		this.lineheight = options.lineheight==undefined?$(this.control)[0].offsetHeight:options.lineheight;
		this.maxlines   = options.maxlines==undefined?8:options.maxlines
		this.width = options.width==undefined?null:options.width
		this.fontsize = options.fontsize==undefined?$(this.control).css("font-size"):options.fontsize
		this.url=null
		this.provide = options.provide
		this.adapter = options.adapter==undefined?null:options.adapter
		this.callback = options.callback==undefined?null:options.callback
		this.ignorenull  = options.ignorenull==undefined?false:options.ignorenull
		this.multword    = options.multword==undefined?false:options.multword
		this.separator   = options.separator==undefined?",":options.separator
		this.init()
	}
	Suggest.prototype.init  = function ()
	{
		this.url = X.ContextRoot()+"/"+this.provide;
		if(this.widget==null)
		{
			this.widget=document.createElement('div')
			$(this.widget).attr("data-x","suggest_widget").attr("data-pid",this.id).addClass("x-suggest").css("font-size",this.fontsize)
			this.widget.innerHTML=''
			this.widget.onscroll=this.OnSugScroll
			var bs=document.getElementsByTagName('body')
			bs[0].appendChild(this.widget)
		}
		this.control.onkeydown = this.onkeydown
		this.control.onkeyup   = this.onkeyup
		this.control.onfocus   = this.onfocus
		document.onclick       = this.OnDocClick
	}
	/// <summary>
	///	静态方法 搜索列表项高亮显示
	/// </summary>
	Suggest.prototype.mousemove = function(idx) 
	{
		if(this.widget.style.display=='none')
		{
			return false;
		}
		if(idx==this.index)
		{
			return true;
		}
		var i;
		var ls = this.widget.getElementsByTagName('li');
		if(this.index>=0&&this.index<ls.length)
		{
			ls[this.index].className='';
		}
		if(idx>=0&&this.index<ls.length)
		{
			ls[idx].className='hover';
		}
		this.index=idx;
	}
	/// <summary>
	/// 判断是否是方向键
	/// </summary>
	Suggest.prototype.isUpDownKey = function(kc)
	{
		//down,up,pageup,pagedown,enter
		if(kc==40 || kc==38 || kc == 33 || kc== 34)
		{	
			return true;
		}
		else
		{
			return false;
		}
	}
	/// <summary>
	/// 判断是否是控制键
	/// </summary>
	Suggest.prototype.isCtrlKey = function(kc)
	{
		//shift,ctrl,alt
		if(kc==16 || kc==17 || kc == 18)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	/// <summary>
	/// 搜索结果DIV滚动事件
	/// </summary>
	Suggest.prototype.OnSugScroll = function(evt)
	{
		evt = evt || window.event;
	    var evtObj = evt.target || evt.srcElement;
		if(this.control==null){return;}
		this.control.focus();
	}
	/// <summary>
	/// document 文档单击事件
	/// </summary>
	Suggest.prototype.OnDocClick = function(evt)
	{
		evt = evt || window.event;
		var evtObj = $(evt.target || evt.srcElement);
		if(evtObj.attr("data-x")!="suggest")
		{
			var widgets  = $('[data-x="suggest_widget"]');
			for(var i=0;i<widgets.length;i++)
			{
				var widget = $(widgets[i]);
				if(widget.css("display") != "none")
				{
					var $this = $('#'+widget.attr("data-pid")).data("bs.suggest")
					var x,y,t,b,l,r;
					var d;
					if(window.event)
					{
						x=event.clientX+document.body.parentNode.scrollLeft;
						y=event.clientY+document.body.parentNode.scrollTop;
					}
					else
					{
						x=e.pageX;
						y=e.pageY;
					}
					d=$this.control;
					if(!d)
					{
						continue;
					}
					t=$(d).offset().top;
					l=$(d).offset().left;
					b=$(d).offset().bottom;
					r=$(d).offset().right;
					if(x>=l && x<r && y>=t && y<b)
					{
						continue;
					}
					d=$this.widget;
					t=$(d).offset().top;
					l=$(d).offset().left;
					b=$(d).offset().bottom;
					r=$(d).offset().right;
					if(x>=l && x<r && y>=t && y<b)
					{
						continue;
					}
					$this.select();
				}
			}
		}
	}
	/// <summary>
	/// 搜索框获得焦点事件
	/// </summary>
	Suggest.prototype.onfocus = function(evt)
	{
		var $this = $(this).data('bs.suggest')
		evt = evt || window.event;
		var evtObj = evt.target || evt.srcElement;
		$this.global_focus_flag = true;
		$this.control = this;
		$this.InputChecking();
		var widgets  = $('[data-x="suggest_widget"]');
		for(var i=0;i<widgets.length;i++)
		{
			var widget = $(widgets[i]);
			if(widget.css("display") != "none" && widget.attr("data-pid")!=$this.id)
			{
				var that = $('#'+widget.attr('data-pid')).data('bs.suggest')
				that.hide();
			}
		}
	}
	/// <summary>
	/// 搜索框失去焦点事件
	/// </summary>
	Suggest.prototype.OnInputBlur = function()
	{
		return;
	}
	/// <summary>
	/// 搜索框输入检查以触发更新
	/// </summary>
	Suggest.prototype.InputChecking = function()
	{
		if(this.control == null) 
		{
			return;
		}
		var v=this.control.value.replace(/(^\s*)|(\s*$)/g,'');
		if(v != "" || this.ignorenull) 
		{  
			this.sendRequest();
		} 
		else 
		{
			this.hide();
			this.control.value = "";
		}
	}
	/// <summary>
	/// 搜索框按键松开事件
	/// </summary>
	Suggest.prototype.onkeyup = function(evt)
	{
		var $this = $(this).data('bs.suggest')
		evt = evt || window.event;
		var evtObj = evt.target || evt.srcElement;
		if($this.control==null)
		{
			$this.control = this;
		}
		var kc=evt.keyCode;
		if($this.InputRealKeyDown(kc,false)&&kc!=13)
		{
			$this.InputChecking();
	    }
	}
	/// <summary>
	/// 搜索框键盘按下事件
	/// </summary>
	Suggest.prototype.onkeydown = function(evt)
	{
		var $this = $(this).data('bs.suggest')
		evt = evt || window.event;
		var evtObj = evt.target || evt.srcElement;
		var bCtrlDown=0;
		if(!evt && window.event)
		{
			evt=window.event;
		}
		if(window.event)
		{
			bCtrlDown=evt.ctrlKey;
		}
		else
		{
			bCtrlDown=(evt.modifiers & Event.CONTROL_MASK) > 0;
		}
		if(bCtrlDown)
		{
			return true;
		}
		var kc=evt.keyCode;
		if($this.isCtrlKey(kc))
		{
			return true;
		}
		return ($this.InputRealKeyDown(kc,true));
	}
	/// <summary>
	/// 对按键进行处理，过滤
	/// </summary>
	Suggest.prototype.InputRealKeyDown = function(kc,isDown)
	{
		this.global_focus_flag = false;
		if(this.isUpDownKey(kc))
		{
			if(isDown)
			{
				if(kc==38)
				{// up
					this.move(1,0);
				}
				else if(kc==40)
				{//down
					this.move(1,1);
				}
				else if(kc==33)
				{//pageup
					this.move(0,0);
				}
				else if(kc==34)
				{//pagedown
					this.move(0,1);
				}
			}
			return false;
		}
		else if(kc==13)
		{//enter
		    if(isDown)
		    {
				this.select();
			}
		    return false;
		}
		else if(kc==9)
		{//tab
		    if(isDown)
			{
				this.select();
			}
			return true;
		}
		else if(kc==27)
		{//esc
			if(isDown)
			{
				this.hide();
			}
			return false;
		}
		return true;
	}
	/// <summary>
	/// 搜索选择事件
	/// </summary>
	Suggest.prototype.select = function() 
	{
		if(this.widget.style.display=='none'){return false;}
		if(this.index>=0 && this.control!=null)
		{
			var li = this.widget.getElementsByTagName("li")[this.index];
			var data = $(li).data();
			if(data.label == "" && this.ignorenull)
			{
				this.hide();
				return;
			}
			if(this.multword)
			{
				var pos = this.control.value.lastIndexOf(this.separator)
				if(pos==-1)
				{
					this.control.value=data.label;
				}
				else
				{
					this.control.value=this.control.value.substring(0,pos+1)+data.label;
				}
				if(this.adapter!=null)
				{
					if(pos==-1)
					{
						$('#'+this.adapter).val(data.key);
					}
					else
					{
						$('#'+this.adapter).val($('#'+this.adapter).val()+this.separator+data.key);
					}
				}
			}
			else
			{
				this.control.value=data.label;
				if(this.adapter!=null)
				{
					$('#'+this.adapter).val(data.key);
				}
			}
			
			this.control.focus();
			if(/msie/.test(navigator.userAgent.toLowerCase()))
			{
				var r=this.control.createTextRange();
				r.move("character", r.text.length);
				r.select();
			}
			else
			{
				var v=this.control.value.length;
				this.control.setSelectionRange(v, v);
			}
			try 
			{  
			   if(this.callback!=null)
			   {
				   eval(this.callback+"(data)");
		       }
		    }catch(e){ }
		}
		this.hide();
	}
	/// <summary>
	/// 获取搜索结果条数
	/// </summary>
	Suggest.prototype.getItemCount = function()
	{
		return this.widget.getElementsByTagName('li').length;
	}
	/// <summary>
	/// 获取搜索结果项目光标移动 选择
	/// </summary>
	Suggest.prototype.move = function(m,n)
	{
		var a=this.index;
		if(m==1&&n==0)
		{
			a--;
		}
		else if(m==1&&n==1)
		{
			a++;
		}
		else if(m==0&&n==0)
		{
			a-=5;
		}
		else if(m==0&&n==1)
		{
			a+=5;
		}
		if(a<0)
		{
			a=this.getItemCount()-1;
		}
		else if(a>=this.getItemCount())
		{
			a=0;
		}
		
		var min = a<this.maxlines?0:(a-this.maxlines+1)
		var max = a
		var s = this.widget.scrollTop/this.lineheight
		if(s<min)
		{
			this.widget.scrollTop=min*this.lineheight;
		}
		else if(s>max)
		{
			this.widget.scrollTop=max*this.lineheight;
		}
		this.mousemove(a);
	}
	/// <summary>
	/// 搜索结果框隐藏
	/// </summary>
	Suggest.prototype.hide = function() 
	{
		if(this.widget.style.display!='none')
		{
			this.widget.style.display='none';
		}
	}
	/// <summary>
	/// 发送请求搜索
	/// </summary>
	Suggest.prototype.sendRequest = function() 
	{
		var $this = this;
		this.index = -1;
		if(this.global_focus_flag)
		{
			return;
		}
		//AJAX请求数据
		var word
		if(this.multword)
		{
			word = this.control.value.substring(this.control.value.lastIndexOf(this.separator)+1)
		}
		else
		{
			word = this.control.value
		}
		var postdata = "&qd=" + encodeURIComponent(word);
		
		$.ajax({url:this.url,data:postdata,cache:false,dataType:'json',
			success:function(data)
			{
				$this.widget.style.left=$($this.control).offset().left +"px";
				if($this.width==null)
				{
					$this.widget.style.width=$this.control.offsetWidth + "px";
				}
				else
				{
					$this.widget.style.width=$this.width + "px";
				}
				var s='<ul>';	
				$.each(data,function(idx,item){     
					s+='<li '+(idx==-1?'class="hover"':'')+' onmousemove="$(\'#'+$this.id+'\').data(\'bs.suggest\').mousemove('+idx+')" data-target="'+$this.id+'" data-key="'+item.key+'" data-label="'+item.label+'" style="height:'+$this.lineheight+'px;line-height:'+$this.lineheight+'px">'+item.label+'</li>'
				})	
				s+='</ul>'
				
				$this.widget.innerHTML=s;
				$this.index=-1;
				$this.widget.scrollTop = 0;
				$this.widget.style.display='block';
				$($this.widget).css("height",(data.length>$this.maxlines?($this.maxlines*$this.lineheight+"px"):""))
				
				var mdh = $(document.body).height()/2
				var mch = $($this.control).offset().top+$($this.control)[0].offsetHeight/2
				if(mch<=mdh)
				{
					$this.widget.style.top = ($($this.control).offset().top+$($this.control)[0].offsetHeight)+"px";
				}
				else
				{
					var height = parseInt($($this.widget).css("height").replace(/(^\s*)|(\s*$)/g,''))
					$this.widget.style.top = ($($this.control).offset().top-height)+"px";
				}
			}
		})
	}
	// Suggest PLUGIN DEFINITION
	// =========================
	function Plugin(option) {
	    return this.each(function () {
	      var $this   = $(this)
	      var data    = $this.data('bs.suggest')
	      //var options = typeof option == 'object' && option
	      //有点特殊
	      var options = typeof arguments[1] == 'object' && $(arguments[1]).data()
	      if (!data) $this.data('bs.suggest', (data = new Suggest(this, options)))
	      if (typeof option == 'string') data[option]()
	    })
	}
	
	var old = $.fn.suggest
	$.fn.suggest             = Plugin
	$.fn.suggest.Constructor = Suggest
	// Suggest NO CONFLICT
	// ===================
	$.fn.suggest.noConflict = function () {
	  $.fn.suggest = old
	  return this
	}
	// Suggest DATA-API
	// ================
	/* 去掉，解决ajax刷新后，事件绑定失效问题
	$(window).on('load.bs.suggest.data-api', function (){
	$('[data-x="suggest"]').each(function () {
		  var $this = $(this)
		  Plugin.call($this, $this.data())
	     })
	})
	*/
}(jQuery);
/*======================================================================
 * 声明式站点菜单控制(定制)
 * Author ：      zhangaoxiang 
 *=====================================================================*/
+function($){
	"use strict";
	var call = '[data-x="menu"],[data-x="xmenu"],[data-x="imenu"]';
	var XMenu = function(el){
		$(el).on('click',call,this.call)
	}
	XMenu.prototype.call = function(e){
		var $this = $(this)
		var selector
		var target = $this.attr('data-target')
        if (target){
        	selector = $('#'+target)
        }else{
        	selector = $this.parent().children('ul')
        }
		var triger =  $this.attr("data-x")
		if(triger=='menu'){
			$('[data-x="submenu"]').hide();
			$('[data-mv="'+target+'"').show();
			layout($('[data-mv="'+target+'"').length)
			$('[data-x="menu"]').removeClass('active')
			$(this).addClass('active');
		}
		else if(triger=='xmenu'){
			selector.toggle()
			$(this).find("span:last").removeClass("vnav-item-angle-down").removeClass("vnav-item-angle-right")
			var show = selector.is(':hidden')
			if(show)
			{
				$(this).find("span:last").addClass("vnav-item-angle-right")
			}
			else
			{
				$(this).find("span:last").addClass("vnav-item-angle-down")
			}
		}
		else if(triger=='imenu'){
			$('[data-x="imenu"]').removeClass('active')
			$(this).addClass('active');
		}
	}
	function layout(length){
		if(length==0){
			$("#vnav-item").css('display','none')
			$("#main-zone").css('left','64px')
		}else{
			$("#vnav-item").css('display','block')
			$("#main-zone").css('left','244px')
		}
	}
	function Plugin(option){
	    return this.each(function (){
		    var $this = $(this)
		    var data  = $this.data('bs.xmenu')
		    console.log(data)
		    if (!data) $this.data('bs.xmenu', (data = new XMenu(this)))
		    if (typeof option == 'string') data[option].call($this)
	  })
    }
	var old = $.fn.xmenu
	$.fn.xmenu             = Plugin
	$.fn.xmenu.Constructor = XMenu
	$.fn.xmenu.noConflict = function () {
	  $.fn.xmenu = old
	  return this
	}
	$(document).on('click.bs.xmenu.data-api', call, XMenu.prototype.call)
}(jQuery);
/*======================================================================
 * 页面加载后，初始化操作
 *====================================================================*/
+function ($) {
	'use strict';
	$(window).on('load', function() {
	  	X.CallBack();
	})
}(jQuery);
